---
title: Cost Optimization  
sidebarTitle: Cost Optimization
description: Minimize costs while maintaining automation performance
---

Cost optimization in Stagehand involves balancing LLM inference costs and browser infrastructure costs. This guide provides practical strategies to reduce your automation expenses.

## Quick Wins

Start with these simple optimizations that can reduce costs:

### 1. Use the Right Model for the Job

We don't recommend using larger, more premium models for simple tasks. See our [evaluation results](https://stagehand.dev/evals) for model performance and cost comparisons across different task types.

<CardGroup cols={2}>
<Card title="Model Selection Guide" icon="brain" href="/configuration/models">
  Choose the right LLM for your budget and accuracy requirements
</Card>
<Card title="Evaluation Results" icon="chart-line" href="https://www.stagehand.dev/evals">
  See how different models perform on different tasks
</Card>
</CardGroup>

### 2. Implement Smart Caching

Cache successful actions to avoid repeated LLM calls. Learn the basics in our [Caching Guide](/best-practices/caching):

<CodeGroup>
```typescript TypeScript
// Cache successful actions
const [action] = await page.observe("Click the sign in button");
await setCache("sign_in_button", action);

// Reuse cached action (no LLM cost)
const cachedAction = await getCache("sign_in_button");
if (cachedAction) {
  await page.act(cachedAction);
} else {
  await page.act(action);
}
```
```python Python
# Cache successful actions
actions = await page.observe("Click the sign in button")
action = actions[0]
await set_cache("sign_in_button", action)

# Reuse cached action (no LLM cost)
cached_action = await get_cache("sign_in_button")
if cached_action:
    await page.act(cached_action)
else:
    await page.act(action)
```
</CodeGroup>

<CardGroup cols={1}>
<Card title="Caching Guide" icon="database" href="/best-practices/caching">
  Reduce costs with smart action caching and observe patterns
</Card>
</CardGroup>

### 3. Optimize Browser Sessions

Reuse sessions when possible and set appropriate timeouts. See [Browser Configuration](/configuration/browser) for details:

<CodeGroup>
```typescript TypeScript
const stagehand = new Stagehand({
  env: "BROWSERBASE",
  browserbaseSessionCreateParams: {
    timeout: 1800, // 30 minutes instead of default 1 hour
    keepAlive: true, // Keep session alive between tasks
  }
});
```
```python Python
stagehand = Stagehand(
    env="BROWSERBASE",
    browserbase_session_create_params={
        "timeout": 1800,  # 30 minutes instead of default 1 hour
        "keep_alive": True,  # Keep session alive between tasks
    }
)
```
</CodeGroup>

<CardGroup cols={1}>
<Card title="Browserbase Cost Optimization" icon="window-maximize" href="https://docs.browserbase.com/guides/cost-optimization">
  Optimize Browserbase infrastructure costs and session management
</Card>
</CardGroup>

## Advanced Strategies

### Intelligent Model Switching

Automatically fall back to cheaper models for simple tasks:

<CodeGroup>
```typescript TypeScript
// Use models from least to most expensive based on task complexity
// See stagehand.dev/evals for performance comparisons
async function smartAct(page: Page, prompt: string) {
  const models = ["cheaper-model", "premium-model"];
  
  for (const model of models) {
    try {
      const stagehand = new Stagehand({ modelName: model });
      await stagehand.init();
      const [action] = await stagehand.page.observe(prompt);
      await stagehand.page.act(action);
      return;
    } catch (error) {
      console.log(`Falling back to ${model}...`);
    }
  }
}
```
```python Python
# Use models from least to most expensive based on task complexity
# See stagehand.dev/evals for performance comparisons
async def smart_act(page, prompt: str):
    models = ["cheaper-model", "premium-model"]
    
    for model in models:
        try:
            stagehand = Stagehand(model_name=model)
            await stagehand.init()
            actions = await stagehand.page.observe(prompt)
            action = actions[0]
            await stagehand.page.act(action)
            return
        except Exception:
            print(f"Falling back to {model}...")
```
</CodeGroup>

### Session Pooling

Reuse browser sessions across multiple tasks:

<CodeGroup>
```typescript TypeScript
class SessionManager {
  private sessions = new Map<string, Stagehand>();
  
  async getSession(taskType: string): Promise<Stagehand> {
    if (this.sessions.has(taskType)) {
      return this.sessions.get(taskType)!;
    }
    
    const stagehand = new Stagehand({ env: "BROWSERBASE" });
    await stagehand.init();
    this.sessions.set(taskType, stagehand);
    return stagehand;
  }
}
```
```python Python
class SessionManager:
    def __init__(self):
        self.sessions = {}
    
    async def get_session(self, task_type: str):
        if task_type in self.sessions:
            return self.sessions[task_type]
        
        stagehand = Stagehand(env="BROWSERBASE")
        await stagehand.init()
        self.sessions[task_type] = stagehand
        return stagehand
```
</CodeGroup>

## Cost Monitoring

Track your spending to identify optimization opportunities. See our [Observability Guide](/configuration/observability) for detailed metrics:

<CodeGroup>
```typescript TypeScript
// Monitor token usage
const metrics = stagehand.metrics;
console.log(`Total tokens: ${metrics.totalPromptTokens + metrics.totalCompletionTokens}`);
console.log(`Estimated cost: $${(metrics.totalPromptTokens + metrics.totalCompletionTokens) * 0.00001}`);
```
```python Python
# Monitor token usage
metrics = stagehand.metrics
total_tokens = metrics['total_prompt_tokens'] + metrics['total_completion_tokens']
print(f"Total tokens: {total_tokens}")
print(f"Estimated cost: ${total_tokens * 0.00001:.4f}")
```
</CodeGroup>

<CardGroup cols={1}>
<Card title="Observability & Metrics" icon="chart-line" href="/configuration/observability">
  Monitor usage patterns and track costs in real-time
</Card>
</CardGroup>

## Budget Controls

Set spending limits to prevent unexpected costs:

<CodeGroup>
```typescript TypeScript
class BudgetGuard {
  private dailySpend = 0;
  private maxDailyBudget: number;
  
  constructor(maxDailyBudget: number = 25) {
    this.maxDailyBudget = maxDailyBudget;
  }
  
  checkBudget(estimatedCost: number): void {
    if (this.dailySpend + estimatedCost > this.maxDailyBudget) {
      throw new Error(`Daily budget exceeded: $${this.maxDailyBudget}`);
    }
    this.dailySpend += estimatedCost;
  }
}
```
```python Python
class BudgetGuard:
    def __init__(self, max_daily_budget: float = 25.0):
        self.daily_spend = 0
        self.max_daily_budget = max_daily_budget
    
    def check_budget(self, estimated_cost: float) -> None:
        if self.daily_spend + estimated_cost > self.max_daily_budget:
            raise Exception(f"Daily budget exceeded: ${self.max_daily_budget}")
        self.daily_spend += estimated_cost
```
</CodeGroup>


## Related Resources

<CardGroup cols={2}>
<Card title="Model Selection Guide" icon="brain" href="/configuration/models">
  Choose the right LLM for your budget and accuracy requirements
</Card>

<Card title="Caching Strategies" icon="database" href="/best-practices/caching">
  Reduce costs with smart action caching and observe patterns
</Card>

<Card title="Observability & Metrics" icon="chart-line" href="/configuration/observability">
  Monitor usage patterns and track costs in real-time
</Card>

<Card title="Browser Configuration" icon="window-maximize" href="/configuration/browser">
  Optimize Browserbase infrastructure costs and session management
</Card>
</CardGroup>